<template>
  <div class="front-sider">
    <div class="logo">
      <img v-show="menuStore.menuFoldStatus" :src="longLogo" class="longLogo" />
      <img v-show="!menuStore.menuFoldStatus" :src="shortLogo" class="shortLogo" />
    </div>

    <div class="menu">
      <a-menu v-if="!isFromShare" mode="inline" :selectedKeys="selectedKeys" :open-keys="openKeys"
        :inline-collapsed="menuStore.menuFoldStatus" @openChange="menuChange" @click="menuClick">
        <a-menu-item v-if="menuStore.isInFront" @click="createdNewChat">
          <template #icon>
            <a-tooltip placement="right">
              <template v-if="!menuStore.menuFoldStatus" #title>新建对话</template>
              <!-- <component :is="item.meta.icon"></component> -->
              <SvgIcon icon-class="IconAddChat" />
            </a-tooltip>
          </template>
          新建对话</a-menu-item>
        <template v-for="item in menuList" :key="item.name">
          <template v-if="!item.children">
            <a-menu-item :key="item.name">
              <template #icon>
                <a-tooltip placement="right">
                  <template v-if="!menuStore.menuFoldStatus" #title>{{ item.meta?.title }}</template>
                  <!-- <component :is="item.meta.icon"></component> -->
                  <SvgIcon :icon-class="item.meta?.icon" />
                </a-tooltip>
              </template>
              {{ item.meta?.title }}
            </a-menu-item>
          </template>
          <a-sub-menu v-if="item.children" :key="item.name">
            <template #icon>
              <a-tooltip placement="right">
                <template v-if="!menuStore.menuFoldStatus" #title>{{ item.meta?.title }}</template>
                <SvgIcon :icon-class="item.meta?.icon as string" />
              </a-tooltip>
            </template>
            <template #title>{{ item.meta?.title }}</template>
            <template #expandIcon></template>
            <div style="overflow-y: scroll; overflow-x: hidden; background: #fff;" :style="historyHight">
              <a-menu-item v-for="child in item.children" :key="child.queryType ? child.id : child" :item="child">
                <template #icon>
                  <SvgIcon v-if="!child?.queryType" :icon-class="child.meta?.icon" />
                  <div v-else class="icon icon-chat-dialog"
                    :class="child?.queryType == 1 ? 'icon-chat-dialog' : 'icon-document-dialog'"></div>
                </template>
                {{ child?.dialogName || child?.meta?.title }}
              </a-menu-item>
            </div>

          </a-sub-menu>
        </template>
        <div class="back-btn" v-if="!menuStore.isInFront && menuStore.menuFoldStatus" @click="goFront">返回系统</div>
      </a-menu>
    </div>
    <div class="personal-box" :class="menuStore.menuFoldStatus ? 'big-personal-box' : 'small-personal-box'">
      <div class="team-box" :class="teamListVisible ? 'actived' : ''" @click="openTeamList"
        v-click-outside="clickTeamOutside">
        <a-tooltip placement="right">
          <template v-if="!menuStore.menuFoldStatus" #title>{{ userStore.userInfo.currentTeamName }}</template>
          <img :src="teamIcon" />
        </a-tooltip>
        <div v-if="menuStore.menuFoldStatus" class="team-name">{{ userStore.userInfo.currentTeamName }}</div>
        <div class="team-list-box" v-if="teamListVisible" v-click-outside="headerListVisible = false">
          <div v-for="item in teamListExceptCur" @click="switchTeam(item)" class="team-list-item ellipsis2" :key="item.id">
            {{ item.teamName }}
          </div>
        </div>
      </div>
      <div class="header-box" v-click-outside="clickHeaderOutside">
        <a-tooltip placement="right">
          <template v-if="!menuStore.menuFoldStatus" #title>{{ userStore.name }}</template>
          <img :src="userStore.logoUrl || defaultHeader" class="avatar" @click="openHeaderList">
        </a-tooltip>
        <div v-if="menuStore.menuFoldStatus" class="name ellipsis" @click="openHeaderList">{{ userStore.name }}</div>
        <div class="fold-button" @click.stop="menuStore.toggleMenuFoldStatus">
          <img :src="menuStore.menuFoldStatus ? iconExpand : iconfold">
        </div>
        <div class="team-list-box header-list-box" v-if="headerListVisible">
          <div class="team-list-item list-item" @click="goPersonalCenter">个人中心</div>
          <div class="team-list-item list-item" @click="handleLogout">退出登录</div>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { message as msgHelper } from 'ant-design-vue'
import { onMounted, ref, watch, computed, provide } from 'vue'
import { useRouter,useRoute } from 'vue-router'
import { useMenuStore } from '@/stores/modules/menu'
import longLogo from '@/static/image/sider/longLogo.png'
import shortLogo from '@/static/image/sider/shortLogo.png'
import teamIcon from '@/static/image/sider/icon-team.png'
import defaultHeader from '@/static/image/sider/default-header.png'
import iconfold from '@/static/image/sider/icon-fold.png'
import iconExpand from '@/static/image/sider/icon_expand.png'
import type { RouteRecordRaw } from 'vue-router'
import { useChatBus } from '@/hook/useChatBus'
import { useUserInfoStore } from '@/stores/modules/userInfo'
import { ROLE_TYPE } from '@/const'
import { apiUserTeamList, apiChangeUserTeam } from '@/api/user'
import { page, saveOrUpdate, remove, apiGetReplyExpireTime } from '@/api/dialog'
import type { IDialogData, PdfFile } from '@/api/type'
import type { RouteRecordNormalized } from 'vue-router'

const menuStore = useMenuStore()
const menuFoldStatus = useMenuStore().menuFoldStatus
const menuList = ref<RouteRecordRaw[]>([])
const openKeys = ref<string[]>([])
const dialogId = ref('')
const dialogName = ref('')
const chatlist = ref<IDialogData[]>([])
const showCreateDialogModal = ref(false)
const isCreatedNewChat = ref(false)
interface TeamList {
  id: string
  expiredTime: string
  peopleLimit: number
  teamName: string
  usedStatus: number
}
const teamListVisible = ref(false)
const headerListVisible = ref(false)
const teamList = ref<TeamList[]>([])
const menuClickFalg = ref<boolean>(false)

const teamListExceptCur = computed(() => {
  return teamList.value.filter(c => c.id !== userStore.userInfo.currentTeamId)
})

// 个人团队列表
const getTeamList = async () => {
  const { data: { entity } } = await apiUserTeamList()
  teamList.value = entity || []
}

const switchTeam = async (teamItem: TeamList) => {
  const { data } = await apiChangeUserTeam({ teamId: teamItem.id })
  if (data.code === '200') {
    msgHelper.success(data.message)
    await userStore.setUserInfo()
    setMenuList()
    if (menuStore.isInFront) {
      router.replace({ name: 'chatDefault' })
      return
    }
    router.replace({ name: 'PersonalCenter' })
  }
}

const clickTeamOutside = () => teamListVisible.value = false
const clickHeaderOutside = () => headerListVisible.value = false

const router = useRouter()
useChatBus((e,params) => {
  switch (e) {
    case 'setMenuList':
      setMenuList()
      break
    case 'refreshDiaglogName':
      setChatList()
      break
    case 'createdNewChat':
      createdNewChat(params)
      break
    default:
      ''
  }
})
const userStore = useUserInfoStore()
const removeOwnerRoute = (arr: RouteRecordRaw[]) => {
  return arr.reduce((acc: any, cur: any) => {
    if (cur.meta?.isOwner) {
      return acc
    }
    if (cur.children?.length) {
      cur.children = removeOwnerRoute(cur.children)
    }
    acc.push(cur)
    return acc
  }, [])
}
const setMenuList = async () => {
  menuList.value = []
  let list = allMenus.value
  if (menuStore.isInFront) {
    await setChatList()
    menuList.value = list.children.reduce((acc, cur) => {
      if (cur.name === 'chatList') {
        cur.children = chatlist.value
      }
      if (cur.meta && !cur.meta.hidden && cur.meta.isFront) {
        acc.push(cur)
      }
      return acc
    }, [])
    // list.children.forEach((item: any) => {
    //   if (item.meta && !item.meta.hidden && item.meta.isFront) {
    //     menuList.value.push(item)
    //   }
    //   if (item.name == 'chatList') {
    //     item.children = chatlist.value
    //   }
    // })
  } else {
    const listArr = list.children.filter((c: RouteRecordNormalized) => !c?.meta?.isFront)
    if (userStore.userInfo.roleType === ROLE_TYPE.所有者) {
      menuList.value = listArr
      return
    }
    if (userStore.userInfo.roleType === ROLE_TYPE.成员) {
      menuList.value = listArr.filter((c: RouteRecordNormalized) => !c.meta?.isAdmin)
      return
    }
    menuList.value = removeOwnerRoute(listArr)
  }
}
const allMenus = ref()
onMounted(() => {
  allMenus.value = router.getRoutes().filter((item => item.name == 'chat' && item?.children.length > 0))[0]
  const backstageRouteNames = allMenus.value.children?.filter((c: RouteRecordNormalized) => !c?.meta?.isFront)?.reduce((acc: Array<string>, cur: any) => {
    if (cur?.children?.length) {
      cur.children.forEach((v: RouteRecordNormalized) => {
        acc.push(v.name as string)
      })
    }
    acc.push(cur.name)
    return acc
  }, [])
  if (backstageRouteNames.includes(route.name)) {
    menuStore.setIsInFront(false)
  }
  setMenuList()
  getTeamList()
  userStore.setUserInfo()
  // getDialogPage()
  getReplyExpireTime()
})
const getReplyExpireTime = async () => {
  if(userStore.replyExpireTime) return 
  const { data: {  entity = 60 }  } = await apiGetReplyExpireTime()
  userStore.setReplyExpireTime(entity * 60 * 1000)
}
const setChatList = async () => {
  await getTopDialogList()
  menuList.value.forEach(element => {
    if (element.name === 'chatList') {
      element.children = chatlist.value
    }
  });
  const first = chatlist.value?.[0]
  //避免详情页重复跳转
  if (first && route.name === 'chatDefault') {
    console.log('route1', route)
    createdNewChat()
  }
  if (chatlist.value.length == 0 && route.name == 'chatDefault') {
    createdNewChat()
  }
}
// const historyHight = computed(()=>
//   `height: calc(100vh- ${menuList.length *50}px-185px)`
// )
const historyHight = computed(() => {
  return menuStore.isInFront ? { height: `calc(100vh -  ${menuList.value.length * 50}px - 225px)` } : {}
})
watch(() => useMenuStore().menuFoldStatus, () => {
  if (useMenuStore().menuFoldStatus == false) {
    openKeys.value = []
    teamListVisible.value = false
    headerListVisible.value = false
  } else {
    openKeys.value = ['chatList']
  }
}, { immediate: true })
const getTopDialogList = async () => {
  return page({
    userId: userStore.id as string,
    pageSize: '20'
  }).then((res) => {
    if (!res.data.ok) return res
    chatlist.value = res.data.entity.rows
    console.log('chatlist', chatlist.value)
    return res
  })
}
const menuChange = (data) => {
  if (data.length > 0 && !menuStore.menuFoldStatus) {
    menuStore.toggleMenuFoldStatus()
  }
  if (menuStore.isInFront) {
    router.push({ name: 'chatList' })
  }
  console.log(data)
}
function getDialogPage() {
  console.log('getDialogPage')
  return getTopDialogList().then((res) => {
    if (!res.data.ok) return
    if (!chatlist.value?.[0]) return
    const first = chatlist.value?.[0]
    //避免详情页重复跳转
    if (first && route.name === 'chatDefault') {
      console.log('route1', route)
      handleSessionItem(first)
    }
  })
}

const menuClick = (item) => {
  if(item.key === 0)  return
  console.log('menuClick', item)
  if (!menuStore.isInFront) {
    router.push(item.key)
    return
  }
  if ((!item.item.item)) {
    if (item.key === 'documentIndex') {
      router.push({ name: 'documentIndex' })
    } else {
      router.push(item.key)
    }
  } else {
    const value = item.item.item
    if (value.queryType === 1) {
      router.push({
        path: `/chat/${value.id}`,
        query: {
          questionTitle: value.dialogName
        }
      })
    } else {
      router.push({
        path: `/chat/documentParsing/${value.id}`
      })
    }

  }
  // router.push({name: item.key})
}
const openTeamList = () => {
  // if(!menuFoldStatus) menuStore.toggleMenuFoldStatus()
  teamListVisible.value = !teamListVisible.value
  if (teamListVisible.value) {
    headerListVisible.value = false
  }
}
const openHeaderList = () => {
  console.log('openHeaderList', menuFoldStatus)
  if (!menuStore.isInFront) return
  // if(!menuFoldStatus && !headerListVisible.value) menuStore.toggleMenuFoldStatus()
  headerListVisible.value = !headerListVisible.value
  if (headerListVisible.value) {
    teamListVisible.value = false
  }
}
const goPersonalCenter = () => {
  // 跳转到个人中心
  menuStore.toggleIsInFront()
  menuList.value = []
  setMenuList()
  headerListVisible.value = false
  router.push({ name: 'PersonalCenter' })
}

function handleLogout() {
  userStore.loginOut().then(() => {
    router.push('/')
  })
}

const goFront = () => {
  menuStore.toggleIsInFront()
  menuList.value = []
  setMenuList()
  router.push({ name: 'chatDefault' })
}

const route = useRoute()
const isFromShare = computed(() => {
  return route.path.includes('loginShareMessage')
})
const selectedKeys = computed(() => {
  console.log('route', route.name)
  if (route.name === 'chatDetail') {
    const keyArr = route.path.split('/chat/')
    console.log('keyArr', keyArr?.[1])
    return [keyArr?.[1] || '']
  }
  if (route.name === 'documentParsing') {
    const keyArr = route.path.split('/chat/documentParsing/')
    console.log('keyArr', keyArr?.[1])
    return [keyArr?.[1] || '']
  }
  console.log('route.name', route.name)
  return [route.name]
})
const createdNewChat = (otherParams?: any) => {
  if(isCreatedNewChat.value) return
  isCreatedNewChat.value = true
  const queryData = {
    id: dialogId.value,
    userId: userStore.id as string,
    dialogName: dialogName.value,
    queryType: 1, //  从导航创建的默认是文档
  }
  if(otherParams) {
    Object.assign(queryData,otherParams)
  }
  saveOrUpdate(queryData).then((res) => {
    if (!res.data.ok) return
    createdCallback()
    showCreateDialogModal.value = false
    isCreatedNewChat.value = false
    dialogId.value = ''
    dialogName.value = ''
  }).catch(() => {
    isCreatedNewChat.value = false
  })
 
}
const createdCallback = () => {
  /**
   * 获取第一个、跳转
   */
  getTopDialogList().then((res) => {
    if (!res.data.ok) return
    const first = chatlist.value?.[0]
    if (!first) return
    handleSessionItem(first)
  })
}
const handleSessionItem = (item: IDialogData) => {
  console.log('handleSessionItem', item)
  router.replace({ path: `/chat/${item.id}`})
}
</script>
<style lang="scss" scoped>
.front-sider {
  display: flex;
  flex-direction: column;
  height: 100vh;
  border-right: 1px solid #f0f0f0;

  /* overflow: hidden; */
  .logo {
    padding: 12px 0;
    display: flex;
    justify-content: center;
    border-bottom: 1px solid #e7e9ec;
    border-right: 1px solid #e7e9ec;

    .longLogo {
      height: 36px;
      width: 168px;
    }

    .shortLogo {
      height: 36px;
      width: 36px;
    }
  }

  .menu {
    flex: auto;

    .icon {
      width: 28px;
      height: 28px;
    }

    .back-btn {
      cursor: pointer;
      width: 198px;
      height: 40px;
      margin: 36px auto 0;
      line-height: 40px;
      background-color: #fff;
      text-align: center;
      border: 1px solid rgba(112, 124, 151, 0.25);

      &:hover {
        background-color: #F5F6F8;
      }
    }
  }

  .personal-box {
    .team-box {
      position: relative;
      cursor: pointer;
    }

    .actived {
      background: #F5F6F8;
    }

    .team-list-box {
      position: absolute;
      right: 0;
      bottom: 0;
      transform: translate(100%, 0);
      z-index: 1000;
      padding: 2px 0;
      background: #fff;
      box-shadow: 0 0 10px rgb(75 156 207 / 40%);

      .team-list-item {
        padding: 8px 16px;
        /* width: 120px; */
        cursor: pointer;
        max-width: 240px;
        max-height: 55px;

        &:hover {
          background-color: #f5f6f8;
        }
      }
    }

    img {
      width: 32px;
      height: 32px;
    }
  }

  .big-personal-box {
    padding-bottom: 19px;

    .team-box {
      display: flex;
      padding: 8px 24px;
      margin-bottom: 4px;
      &:hover {
        background-color: #F5F6F8;
      }

      .team-name {
        font-size: 16px;
        line-height: 32px;
        margin-left: 16px;
        overflow: hidden;
        text-wrap: nowrap;
        text-overflow: ellipsis;
        color: #0D1C2E;
      }
    }

    .header-box {
      display: flex;
      padding: 8px 24px;
      position: relative;
      &:hover {
        background-color: #F5F6F8;
      }

      .name {
        font-size: 16px;
        color: #0D1C2E;
        line-height: 32px;
        margin-left: 12px;
      }

      .fold-button {
        cursor: pointer;
        margin-left: auto;
      }
    }
  }

  .small-personal-box {
    padding: 0 14px 24px;

    .team-box {
      margin-bottom: 20px;
    }

    .header-box {
      .fold-button {
        cursor: pointer;
        margin-top: 24px;
      }
    }
  }

  .header-box {
    position: relative;
    transition: .4s;

    .avatar,
    .name {
      cursor: pointer;
    }
    .avatar {
      border-radius: 50%;
    }

    .header-list-box {
      position: absolute;
      right: 0;
      left: unset;
      top: unset;
      bottom: 0;
      transform: translate(100%, 0);
      box-shadow: 0 0 10px rgb(75 156 207 / 40%);
      z-index: 5;

      .list-item {
        cursor: pointer;

        &:hover {
          background-color: #f5f6f8;
        }
      }
    }
  }
}

:deep() {
  .ant-menu-item {
    padding-left: 0;
    &:hover {
      background-color: #F5F6F8;
    }
  }

  .ant-menu-submenu,
  .ant-menu-item {
    .svg-icon.svg-icon {
      font-size: 28px;
    }
  }
}

.ant-menu-inline.ant-menu-root .ant-menu-submenu-title {
  display: none;
}
.ant-menu-inline {
  border-right: unset;
}

::-webkit-scrollbar {
  width: 0px;
  /* 宽度 */
}
</style>